/**
 * @description 权益特征事件
 * @author muisuidaan
 */
import React, { useState, useEffect, ReactNode } from "react";

// import { Progress, Popover } from "antd";
import EventDetail from "@/components/FOF/EventDetail";
import LittleTitle from "@/components/Title/littleTitle";
import Pie from "@/components/EchartsComponents/Pie/pie";
import EventEmpty from "@/components/FOF/EventEmpty";

import { getDataFromObject } from "@/utils/utils";

import { getBaseColors, getExpandColors } from "@/utils/echarts";

// import * as echarts from "echarts";
import { queryPortfolioEventList } from "./../../PortfolioOverview/portfolio";
import { queryPortFolioEvent } from "../fixedAssets";

import cn from "classnames";

import styles from "./index.less";
import styled from "@/pages/PortfolioOverview/components/EventList/index.less";

interface infoProps {
  [key: string]: string | number | null;
}
interface Props {
  kind: string; //说明类型
  info: infoProps;
  title: string | number;
  children: ReactNode | string; //图表区域
  stockHasRequest:boolean;//请求完成
}

import { getUrlParam } from "@/utils/utils";



export const MessageTitle = ({ event,changeCardState }) => {
  
  return (
    <div 
      className={styled.event_list_container}
      onClick={() => {
        changeCardState(event);
      }}
    >
      <p
        className={
          event?.messageType == 1 ? styled.icon_warnning : styled.icon_message
        }
      ></p>
      <p 
        // className={cn(
        //   styled.event_list_text,
        //   event?.open ? styled.event_list_text_active : null,
        // )}
        style={{fontSize:13}}

        className={cn(
          styled.event_list_text,styled.event_list_text_active 
        )}
      >
        {event?.eventDate || "-"} {event?.eventHeader || "-"}
      </p>
      <p
        className={cn(
          styled.show_button,
          event.open ? styled.show_button_active : null
        )}
       
      ></p>
    </div>
  );
};
export const EventListContainer = ({
  item,
  children,
  changeCardState,
  eventCode,
  portfolioCode,
}) => {
  const [eventData, setEventData] = useState<any>({});
  const eventCodeUrl = getUrlParam("eventCode"); //事件codeß
  const eventId = getUrlParam("eventId"); //事件id
  const time = getUrlParam("time"); // 重复点击一个内容时用这个来触发

  useEffect(() => {
    if (!item?.open) return;
    queryPortFolioEvent({
      eventCode,
      portFolioCode: portfolioCode,
    }).then((res) => {
      if (res?.code === "0") {
        setEventData(getDataFromObject(res?.data || {}));
      }
    });
    // switch (item.key) {
    //   case 1:

    //     break;

    //   default:
    //     break;
    // }
  }, [item?.open, eventCode]);
  return (
    <div 
        className={styles.info_card} id={item.eventCode + item.id}
        // onClick={() => {
        //   changeCardState(item);
        // }}
      >
        <MessageTitle
          changeCardState={changeCardState}
          event={{
            ...item,
          }}
        />
        {item.open && (
          <div >
            <EventDetail
              type="assets"
              className={styles.assets_event_detail}
              children={
                eventData?.axis?.length > 0? (<div style={{ width: "100%", height: 132 }}>
                   
                    <Pie
                      name=""
                      idName={`credit-pie${eventCode}${portfolioCode}`}
                      legendData={eventData?.axis.map((v) => v.key)}
                      pieData={eventData?.axis.map((v) => ({
                        ...v,
                        name: v.key,
                      }))}
                      legendProps={{
                        left: "45%",
                        top: "middle",
                        itemGap:0,
                        // itemWidth:10,
                        type:"plain",
                        textStyle: {
                          padding: [4, 15, 0, 0],
                          // width:500,
                          backgroundColor:"transparent",
                          color: '#35425e',
                          fontSize: 10,
                          
                        }
                      }}
                      pieStyle={{
                        width: "90%",
                        height: "90%",
                        radius: ["60%", "89%"],
                      }}
                      seriesType={{
                        left:"-10%"
                      }}
                      formatLen={4}
                      color={[...getBaseColors(), ...getExpandColors()]}
                    />
                   
                </div>): (
                    <EventEmpty
                      title="暂无数据"
                      // style={{ paddingTop: 0}}
                      // imgStyle={{width:149,height:102}}
                    ></EventEmpty>
                  )
              }
              info={{
                ...item,
              }}
            />
          </div>
        )}
      </div>
    
  );
};

const AssetsCard = (props: Props) => {
  const eventCodeUrl = getUrlParam("eventCode"); //事件codeß
  const eventId = getUrlParam("eventId"); //事件id
  const time = getUrlParam("time"); // 重复点击一个内容时用这个来触发
  const { info = {}, title, children, kind,stockHasRequest } = props || {};
  // console.log("AssetsCard", props);
  const { eventCode, portfolioCode, key,littleName } = info || {};

  const [eventList, setEventList] = useState([]);
  const [hasRequest, setHasRequest] = useState(false);

  const _handleScroll = () => {
    const scroll_item = document.getElementById(eventCodeUrl + eventId);
    if (scroll_item) {
      const offsetHeight = scroll_item.offsetHeight;
      const documentH = document.body.clientHeight;
      const compareH = documentH>(offsetHeight+300)?(documentH-offsetHeight-50):documentH/1.7;
      scroll_item.offsetParent.scrollTop = scroll_item.offsetTop - compareH;
      
    }
  }

  useEffect(() => {
    // console.log(hasRequest && eventId && eventCodeUrl&&stockHasRequest)
    // console.log(hasRequest , eventId , eventCodeUrl ,stockHasRequest)
    if (hasRequest && eventId && eventCodeUrl&&stockHasRequest) {
      changeCardState({
        id: eventId,
      });
      //滚动到可视区域里

      
      // requestAnimationFrame(_handleScroll)
      //雨薇要求元素底部固定在可视区里，所以需要等元素打开后计算元素的高度
      setTimeout(() => {
        requestAnimationFrame(_handleScroll);
      }, 0);
    }
  }, [eventCodeUrl, eventId, hasRequest,time,stockHasRequest]);

  useEffect(() => {
    setHasRequest(false);
    switch (key) {
      case 1:
        //股票行业分布（申万）
        queryPortfolioEventList({
          eventCodes: ["portfolio_industry_concentration_sw"],
          portfolioCode,
        }).then((res) => {
          if (res.code === "0" && res.data?.length > 0) {
            setEventList(res.data);
          } else {
            setEventList([]);
          }
          setHasRequest(true);
        });

        break;
      case 2:
        //股票行业分布（中证）
        queryPortfolioEventList({
          eventCodes: ["portfolio_industry_concentration_zz"],
          portfolioCode,
        }).then((res) => {
          if (res.code === "0" && res.data?.length > 0) {
            setEventList(res.data);
          } else {
            setEventList([]);
          }
          setHasRequest(true);
        });

        break;
      case 3:
        //板块集中度
        queryPortfolioEventList({
          eventCodes: ["portfolio_section_concentration_zz"],
          portfolioCode,
        }).then((res) => {
          if (res.code === "0" && res.data?.length > 0) {
            setEventList(res.data);
          } else {
            setEventList([]);
          }
          setHasRequest(true);
        });

        break;

      default:
        break;
    }
  }, []);

  const changeCardState = (event: infoProps) => {
    const newList =
      eventList?.length > 0
        ? eventList?.map((item) => ({
            ...item,
            open: item.id == event.id ? !item.open : item.open,
          }))
        : [];
    setEventList(newList);
  };

  return (
    <div className={styles.assets_card_wrapper}>
      <div style={{display:'flex'}}>
        <LittleTitle title={title?.toLocaleString()}></LittleTitle>

        {littleName &&(
          <p className={styles.little_name_text}>{littleName}</p>
        )}
      </div>
      {eventList?.length > 0 && kind === "1" ? (
         <div className={styles.assets_card_container} >
         {children}
         {
           eventList.map((item, index) => {
            return (
             
              <EventListContainer
                key={item.id || index}
                item={{ ...item, key }}
                children={children}
                changeCardState={changeCardState}
                eventCode={eventCode}
                portfolioCode={portfolioCode}
              />
            );
          })
         }
         
       </div>
        
      ) : kind === "2" ? (
        <div className={styles.assets_card_container}>
          {children}
          {info.textMessage && (
            <div
              className={styles.bottom_gray_text}
              dangerouslySetInnerHTML={{
                __html: info.textMessage?.toLocaleString(),
              }}
            ></div>
          )}
        </div>
      ) : (
        <div className={styles.assets_card_container}>{children}</div>
      )}
    </div>
  );
};

export default AssetsCard;
